<?php
/**
 * Created by PhpStorm.
 * User: mr_lee
 * Date: 2017/10/17
 * Time: 上午10:09
 */

namespace app\index\controller;


use Alipay\Alipayobj;
use app\common\controller\Deviceobj;
use app\common\controller\FeiePrint;
use app\common\model\Agent;
use app\common\model\Merchant;
use app\common\model\Paylog;
use think\Controller;

class Alipaytest extends Controller
{
    private $uid;

    public function pay()
    {
        $request = request();
        $Merchant = new Merchant();
        $users = $Merchant->where(array('id' => $request->param('id')))->find();
        if ($users['ali_merid'] == '') {
            $this->error('当前商户未开启支付宝支付功能');
        }
        $Agent = new Agent();
        $agent = $Agent->where(array('id' => $users['agent']))->find();
        $raskey = $agent['ali_app_key'];
        $options = array(
            //'token' => $config ["token"], // 填写你设定的key
            //'encodingaeskey' => $config ["encodingaeskey"], // 填写加密用的EncodingAESKey
            'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
            'rsaPrivateKey' => $agent['ali_app_key'],
        );
        $aliObj = new Alipayobj($options);
        if ($request->get('auth_code')) {
            $param['app_id'] = $agent['ali_app_id'];
            $param['method'] = "alipay.system.oauth.token";
            $param['charset'] = "UTF-8";
            $param['sign_type'] = "RSA2";
            $param['version'] = '1.0';
            $param['timestamp'] = date('Y-m-d H:i:s');
            $param['grant_type'] = 'authorization_code';
            $param['code'] = $request->get('auth_code');
            $signContent = $aliObj->rsaSign($param, $signType = "RSA2");

            $param['sign'] = $signContent;
            $uid = $aliObj->getuid($param);
            $user = json_decode($uid, true);
            $uid = $user['alipay_system_oauth_token_response']['user_id'];
//            echo $uid;
            $this->assign("headimg", $users['img']);
            $this->assign('shmc', $users['merchant']);
            $this->assign('id', $request->param('id'));
            $this->assign('uid', $uid);
            $this->assign('mach', $users);
            $this->assign("channel", "alipay");

            return $this->fetch('alipay');

        } else {
            $callback = 'https://' . $_SERVER ['SERVER_NAME'] . url("Alipay/pay", array('id' => $request->param('id')));
            $url = $aliObj->getOauthRedirect($callback, '', 'auth_base');
//        echo $url;
//        exit();
            header("Location: $url");
        }

    }

    public function alipaypay()
    {
        $request = request();
        $Paylog = new Paylog();
        $orderid = request()->post('orderid');
        $norderid = $Paylog->where(array('orderid' => $orderid))->count();
        if ($norderid != 0) {
            echo 1;

        } else {
            $orderid = request()->post('orderid');
            $Paylog = new Paylog();
            $Paylog->allowField(true)->save(['orderid'=>$orderid]);
//            $orderid="s0000-1123393993".rand(1,999);
            $Merchant = new Merchant();
            $Agent = new Agent();
            $users = $Merchant->where(array('id' => $request->param('id')))->find();
            $agent = $Agent->where(array('id' => $users['agent']))->find();
            $raskey = $agent['ali_app_key'];
            $options = array(
                //'token' => $config ["token"], // 填写你设定的key
                //'encodingaeskey' => $config ["encodingaeskey"], // 填写加密用的EncodingAESKey
                'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
                'rsaPrivateKey' => $agent['ali_app_key'],

            );
            $aliObj = new Alipayobj($options);

            $price = request()->post('price');
            $buyer_id = request()->post('buyer_id');
            $out_trade_no = $orderid;
            $body = "快捷支付";
            $total_fee = $price;
            $data['app_id'] = $agent['ali_app_id'];
            $data['method'] = "alipay.trade.create";
            $data['charset'] = "UTF-8";
            $data['sign_type'] = "RSA2";
            $data['timestamp'] = date('Y-m-d H:i:s');
            $data['version'] = "1.0";
            $data['notify_url'] = 'https://' . $_SERVER ['SERVER_NAME'];
            $data['app_auth_token'] = $users['ali_merid'];
            $data['biz_content'] = json_encode(array(
                'out_trade_no' => $out_trade_no,
                'total_amount' => $total_fee,
                'subject' => $body,
                'buyer_id' => $buyer_id,
                'alipay_store_id' => $users['ali_store_id'],
//                'store_id'=>I('get.id'),
                'extend_params' => array(
                    'sys_service_provider_id' => $agent['sys_service_provider_id'],
                ),

            ));
            $signContent = $aliObj->rsaSign($data, $signType = "RSA2");


            $data['sign'] = $signContent;
            $uid = $aliObj->getuid($data);
            $user = json_decode($uid, true);
            $orderid = $user['alipay_trade_create_response']['trade_no'];
            $sdata['orderid'] = $out_trade_no;
            $sdata['mid'] = $request->param('id');
            $sdata['openid'] = request()->post('buyer_id');
            $sdata['pay_statu'] = 0;
            $sdata['price'] = $price;
            $sdata['yf_price'] = $price;
            $sdata['add_time'] = time();
            $sdata['pay_fs'] = 1;
            $Paylog = new Paylog();
            $add = $Paylog->allowField(true)->save($sdata,['orderid'=>$out_trade_no]);
            return json($orderid);
        }


    }

    public function payover()
    {
        $request = request();
        $Merchant = new Merchant();
        $Agent = new Agent();
        $users = $Merchant->where(array('id' => $request->param('id')))->find();
        $agent = $Agent->where(array('id' => $users['agent']))->find();
        $raskey = $agent['ali_app_key'];
        $options = array(
            //'token' => $config ["token"], // 填写你设定的key
            //'encodingaeskey' => $config ["encodingaeskey"], // 填写加密用的EncodingAESKey
            'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
            'rsaPrivateKey' => $agent['ali_app_key'],

        );
        $aliObj = new Alipayobj($options);
        $appid = $agent['ali_app_id'];
        $data['app_id'] = $appid;
        $data['method'] = 'alipay.trade.query';
        $data['charset'] = "UTF-8";
        $data['sign_type'] = "RSA2";
        $data['timestamp'] = date('Y-m-d H:i:s');
        $data['version'] = "1.0";
        $data['app_auth_token'] = $users['ali_merid'];
        $data['biz_content'] = json_encode(array(
            'out_trade_no' => $request->param('orderid')
        ));
        $signContent = $aliObj->rsaSign($data, $signType = "RSA2");
        $data['sign'] = $signContent;
        $uid = $aliObj->getuid($data);
        $user = json_decode(iconv("GB2312", "UTF-8//IGNORE", $uid), true);
        $payinfos = $user['alipay_trade_query_response'];

        file_put_contents('/data2/html/osapi/66666.txt', json_encode($payinfos), 8);
        $orderstatu = $user['alipay_trade_query_response']['trade_status'];

        if ($orderstatu == "TRADE_SUCCESS") {
//            $data['pay_statu'] = 1;
//            $data['orderno'] = $payinfos['trade_no'];
//            $data['pay_time'] = $payinfos['send_pay_date'];
//            $data['payinfo'] = json_encode($payinfos,JSON_UNESCAPED_UNICODE);
//            file_put_contents('/data2/html/osapi/2333.txt',json_encode($data),8);
//            $Paylog = new Paylog();
//            $Paylog->save($data, ['orderid' => $payinfos['out_trade_no']]);
            $orderid = $request->param('orderid');
            $this->order_query($orderid);
            $data['code'] = 0;

        } else {

            $data['code'] = 1;
        }
        return json($data);
    }

    public function order_query($out_trade_no)
    {
        $Paylog = new Paylog();
        $map['orderid'] = $out_trade_no;
        $payinfos2 = $Paylog->where($map)->find();


        $Merchant = new Merchant();
        $Agent = new Agent();
        $users = $Merchant->where(array('id' => $payinfos2['mid']))->find();
        $agent = $Agent->where(array('id' => $users['agent']))->find();
        $raskey = $agent['ali_app_key'];
        $options = array(
            //'token' => $config ["token"], // 填写你设定的key
            //'encodingaeskey' => $config ["encodingaeskey"], // 填写加密用的EncodingAESKey
            'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
            'rsaPrivateKey' => $agent['ali_app_key'],

        );

        $aliObj = new Alipayobj($options);
        $appid = $agent['ali_app_id'];

        $data['app_id'] = $appid;
        $data['method'] = 'alipay.trade.query';
        $data['charset'] = "UTF-8";
        $data['sign_type'] = "RSA2";
        $data['timestamp'] = date('Y-m-d H:i:s');
        $data['version'] = "1.0";
        $data['app_auth_token'] = $users['ali_merid'];
        $data['biz_content'] = json_encode(array(
            'out_trade_no' => $payinfos2['orderid']
        ));
        $signContent = $aliObj->rsaSign($data, $signType = "RSA2");
        $data['sign'] = $signContent;
        $uid = $aliObj->getuid($data);
        $user = json_decode(iconv("GB2312", "UTF-8//IGNORE", $uid), true);
        $payinfos = $user['alipay_trade_query_response'];
        if ($payinfos['trade_status'] == "TRADE_SUCCESS") {
            $datas['pay_statu'] = 1;
            $datas['orderno'] = $payinfos['trade_no'];
            $datas['pay_time'] = $payinfos['send_pay_date'];
            $datas['payinfo'] = json_encode($payinfos);
            $Paylog = new Paylog();
            $Paylog->save($datas, ['id' => $payinfos2['id']]);
            if ($payinfos2['tzzt'] == 0) {
                $s = action('Wxauth/sendtemplate', array($payinfos2['mid'], $payinfos2['orderid']));
                $FeiePrint = new FeiePrint();
                $FeiePrint->sendprint($payinfos2['orderid']);
                $Deviceobj = new Deviceobj();
                $s=$Deviceobj->ylb_sendvoice($payinfos2['orderid']);
//                action('Index/sendprint', array($payinfos2));
                $da['tzzt'] = 1;
                $da['tzmsg'] = json_encode($s);
                $Paylog->save($da, ['id' => $payinfos2['id']]);
            }

        }

    }


    public function orderinfo()
    {

        $Adview = new Adview();
        $request = request();
        $ad_type = $Adview->getadtype($request->param('orderid'));
        $Adview->getadvert($request->param('orderid'));
        $Merchant = new Merchant();
        $Agent = new Agent();
        $users = $Merchant->where(array('id' => $request->param('id')))->find();
        $agent = $Agent->where(array('id' => $users['agent']))->find();
        $raskey = $agent['ali_app_key'];
        $options = array(
            //'token' => $config ["token"], // 填写你设定的key
            //'encodingaeskey' => $config ["encodingaeskey"], // 填写加密用的EncodingAESKey
            'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
            'rsaPrivateKey' => $agent['ali_app_key'],

        );
        $aliObj = new Alipayobj($options);

        if ($request->param('auth_code') || request()->get('auth_code')) {
            $param['app_id'] = $agent['ali_app_id'];
            $param['method'] = "alipay.system.oauth.token";
            $param['charset'] = "UTF-8";
            $param['sign_type'] = "RSA2";
            $param['version'] = '1.0';
            $param['timestamp'] = date('Y-m-d H:i:s');
            $param['grant_type'] = 'authorization_code';
            $param['code'] = $request->param('auth_code') ? $request->param('auth_code') : $request->get('auth_code');
            $signContent = $aliObj->rsaSign($param, $signType = "RSA2");

            //$sign2 = $aliObj->alonersaSign($signContent, $raskey, $signType = "RSA", $keyfromfile = false);


            $param['sign'] = $signContent;
            $uid = $aliObj->getuid($param);
            $user = json_decode($uid, true);
            $this->uid = $user['alipay_system_oauth_token_response']['user_id'];
//            var_dump($uid);
        } else {
            $callback = 'https://' . $_SERVER ['SERVER_NAME'] . url("Alipay/orderinfo", array('id' => $request->param('id'), 'orderid' => $request->param('orderid')));
            $url = $aliObj->getOauthRedirect($callback, '', 'auth_userinfo');
            header("Location: $url");
        }


        $maq['orderid'] = $request->param('orderid');
        $Paylog = new Paylog();
        $order = $Paylog->where($maq)->find();
//        echo $this->uid;
//        echo "<br />";
//        echo $order['openid'];
//        exit();

//        if ($this->uid == $order['openid']) {
        $mav['id'] = $request->param('id');
        $Merchant = new Merchant();
        $shmc = $Merchant->where($mav)->value('merchant');


        $this->assign('shmc', $shmc);
        $this->assign('order', $order);
        $this->assign('id', $request->param('id'));
        $this->assign('orderid', $request->param('orderid'));
//        } else {
//            $this->error('非订单支付者无法查看订单详情');
//        }
        return $this->fetch("alipay/orderinfo");
    }

    public function getorder2()
    {
        $request = request();
        if ($request->isAjax()) {
            $sh = $request->post('id');
            $order = "H" . $sh . "-" . date('YmdHis') . rand(10000, 99999);
            echo $order;
        }
    }

    public function getmerid()
    {
        $Merchant = new Merchant();
        $Agent = new Agent();

        $users = $Merchant->where(array('id' => 602))->find();
        $agent = $Agent->where(array('id' => $users['agent']))->find();
        $raskey = $agent['ali_app_key'];
        $options = array(
            //'token' => $config ["token"], // 填写你设定的key
            //'encodingaeskey' => $config ["encodingaeskey"], // 填写加密用的EncodingAESKey
            'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
            'rsaPrivateKey' => $agent['ali_app_key'],

        );
        $aliObj = new Alipayobj($options);
        $param['app_id'] = $agent['ali_app_id'];
        $param['method'] = "alipay.offline.market.shop.batchquery";
        $param['charset'] = "UTF-8";
        $param['sign_type'] = "RSA2";
        $param['version'] = '1.0';
        $param['timestamp'] = date('Y-m-d H:i:s');
        $param['app_auth_token'] = $users['ali_merid'];
        $param['biz_content'] = json_encode(array(
            'page_no' => 1
        ));
        $signContent = $aliObj->rsaSign($param, $signType = "RSA2");
        $param['sign'] = $signContent;
        $uid = $aliObj->getuid($param);
        $user = json_decode($uid, true);
        var_dump($user);

    }

}